const { Model, Schema } = require('../helps/model');
const { formatData } = require('../helps/tools');
// const { executor } = require('../helps/model');
// CREATE TABLE `banner_relation` (
//   `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
//   `banner_id` int(11) unsigned NOT NULL COMMENT '关联banner',
//   `module` varchar(255) NOT NULL COMMENT '对应模块',
//   `module_id` int(11) unsigned NOT NULL COMMENT '对应模块id',
//   `order` int(11) unsigned NOT NULL DEFAULT 0 COMMENT '排序',
//   `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
//   `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
//   PRIMARY KEY (`id`),
//   KEY `banner` (`banner_id`) USING BTREE
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Banner关系表';

const schema = new Schema({
  primary: 'id',
  create_time: true,
  update_time: true,
  soft_delete: true,
  auto_increment: true,
  fields: ['id', 'banner_id', 'module', 'module_id', 'order'],
  default: {
    order: 0,
  },
});

export const model = new Model('banner_relation', schema);

/**
 * 查找
 * @param id
 * @returns {*}
 */
export function get(id) {
  return model.findByKey(id);
}

/**
 * 查找列表
 * @param ids
 * @returns {*}
 */
export function getIds(ids) {
  return model.findByQuery({
    where: [
      ['id', 'in', ids],
    ],
  });
}

/**
 * 创建
 * @param data
 * @returns {*}
 */
export function add(data) {
  return model.insert(formatData(schema.baseFields(), data));
}

/**
 * 更新
 * @param id
 * @param data
 * @returns {*}
 */
export function put(id, data) {
  return model.updateByKey(id, formatData(schema.baseFields(), data));
}

/**
 * 删除
 * @param id
 * @returns {*}
 */
export function del(id) {
  return model.deleteByKey(id);
}

/**
 * 列表分页
 * @param page
 * @param number
 * @returns {*}
 */
export function search(where, page = 1, number = 50, order = 'id', direction = 'desc') {
  return model.findListAndCount(where, page, number, `\`${order}\` ${direction}`);
}

export function list(page, number, order, direction) {
  return search([], page, number, order, direction);
}

export function listByBanner(banner_id, page, number, order, direction) {
  return search([
    ['banner_id', '=', banner_id],
  ], page, number, order, direction);
}

export function all(banner_id, order, direction) {
  return model.findByQuery({
    where: [
      ['banner_id', '=', banner_id],
    ],
    order: `\`${order}\` ${direction}`,
  });
}
